// 性能优化工具类

/**
 * 防抖函数
 * @param func 要防抖的函数
 * @param wait 等待时间
 * @param immediate 是否立即执行
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  immediate = false
): (...args: Parameters<T>) => void {
  let timeout: number | null = null;
  
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null;
      if (!immediate) func(...args);
    };
    
    const callNow = immediate && !timeout;
    
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    
    if (callNow) func(...args);
  };
}

/**
 * 节流函数
 * @param func 要节流的函数
 * @param limit 时间间隔
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean;
  
  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

/**
 * 内存管理
 */
export class MemoryManager {
  private cache: Map<string, any> = new Map();
  private maxSize: number;
  private currentSize = 0;
  
  constructor(maxSize = 50) {
    this.maxSize = maxSize;
  }
  
  set(key: string, value: any) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.currentSize >= this.maxSize) {
      // 删除最旧的项
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
      this.currentSize--;
    }
    
    this.cache.set(key, value);
    this.currentSize++;
  }
  
  get(key: string) {
    if (this.cache.has(key)) {
      const value = this.cache.get(key);
      // 移到最后（LRU策略）
      this.cache.delete(key);
      this.cache.set(key, value);
      return value;
    }
    return null;
  }
  
  has(key: string) {
    return this.cache.has(key);
  }
  
  delete(key: string) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
      this.currentSize--;
      return true;
    }
    return false;
  }
  
  clear() {
    this.cache.clear();
    this.currentSize = 0;
  }
  
  size() {
    return this.currentSize;
  }
}

/**
 * 网络请求优化
 */
export class RequestOptimizer {
  private pendingRequests: Map<string, Promise<any>> = new Map();
  private cache: MemoryManager;
  
  constructor(cacheSize = 100) {
    this.cache = new MemoryManager(cacheSize);
  }
  
  async request(url: string, options: any = {}, useCache = true) {
    const cacheKey = `${url}_${JSON.stringify(options)}`;
    
    // 检查缓存
    if (useCache && this.cache.has(cacheKey)) {
      return this.cache.get(cacheKey);
    }
    
    // 检查是否有相同的请求正在进行
    if (this.pendingRequests.has(cacheKey)) {
      return this.pendingRequests.get(cacheKey);
    }
    
    // 发起新请求
    const requestPromise = new Promise((resolve, reject) => {
      uni.request({
        url,
        ...options,
        success: (response: any) => {
          // 缓存结果
          if (useCache && response.statusCode === 200) {
            this.cache.set(cacheKey, response.data);
          }
          
          // 清除pending状态
          this.pendingRequests.delete(cacheKey);
          
          resolve(response.data);
        },
        fail: (error: any) => {
          // 清除pending状态
          this.pendingRequests.delete(cacheKey);
          reject(error);
        }
      });
    });
    
    this.pendingRequests.set(cacheKey, requestPromise);
    return requestPromise;
  }
  
  clearCache() {
    this.cache.clear();
  }
  
  cancelPendingRequests() {
    this.pendingRequests.clear();
  }
}

/**
 * 页面性能监控
 */
export class PerformanceMonitor {
  private metrics: Map<string, number> = new Map();
  
  startTiming(name: string) {
    this.metrics.set(`${name}_start`, Date.now());
  }
  
  endTiming(name: string) {
    const startTime = this.metrics.get(`${name}_start`);
    if (startTime) {
      const duration = Date.now() - startTime;
      this.metrics.set(name, duration);
      console.log(`[Performance] ${name}: ${duration}ms`);
      return duration;
    }
    return 0;
  }
  
  getTiming(name: string) {
    return this.metrics.get(name) || 0;
  }
  
  getAllMetrics() {
    const result: Record<string, number> = {};
    this.metrics.forEach((value, key) => {
      if (!key.endsWith('_start')) {
        result[key] = value;
      }
    });
    return result;
  }
  
  clear() {
    this.metrics.clear();
  }
}

// 全局性能优化实例
export const globalPerformanceMonitor = new PerformanceMonitor();
export const globalRequestOptimizer = new RequestOptimizer();
export const globalMemoryManager = new MemoryManager();

// 工具函数
export const performanceUtils = {
  // 延迟执行
  delay: (ms: number) => new Promise(resolve => setTimeout(resolve, ms)),
  
  // 批量执行
  batch: async (tasks: (() => Promise<any>)[], batchSize = 5) => {
    const results = [];
    for (let i = 0; i < tasks.length; i += batchSize) {
      const batch = tasks.slice(i, i + batchSize);
      const batchResults = await Promise.all(batch.map(task => task()));
      results.push(...batchResults);
      
      // 让出控制权
      await new Promise(resolve => setTimeout(resolve, 0));
    }
    return results;
  },
};